/**
 * @description 搭建 http 服务
 * @author xfj
 */

const http = require('http');
const fs = require('fs');
const path = require('path');
const etag = require('etag');

const server = http.createServer();

server.on('request', (req, res) => {
  console.log(req.url);
  if('/'.startsWith(req.url)) {
    const data = readFile(path.join(__dirname, 'index.html'));
    res.end(data);
    return;
  } else if('/a.js'.startsWith(req.url)) {
    const data = readFile(path.join(__dirname, 'a.js'));
    // 方式一
    res.setHeader("Cache-Control", `max-age=10`);
    // 方式二（不推荐）
    // res.setHeader("expires", new Date('2022-02-28 16:56').toUTCString());
    res.end(data);
    return;
  } else if('/b.js'.startsWith(req.url)) {
    // 协商缓存方式一
    const filepath = path.join(__dirname, 'b.js');
    const { mtimeMs } = fs.statSync(filepath);
    if(req.headers['if-modified-since'] == mtimeMs) {
      res.statusCode = 304;
      res.end('');
      return;
    }

    res.setHeader("Cache-Control", 'no-cache');
    res.setHeader("Last-Modified", mtimeMs);
    const data = readFile(filepath);
    res.end(data);
    return;
  }  else if('/c.js'.startsWith(req.url)) {
    // 协商缓存方式二
    const filepath = path.join(__dirname, 'c.js');
    const data = readFile(filepath);
    const contentId = etag(data);
    if(req.headers['if-none-match'] == contentId) {
      res.statusCode = 304;
      res.end('');
      return;
    }
    res.setHeader("Cache-Control", 'no-cache');
    res.setHeader('ETag', contentId)
    res.end(data);
    return;
  }
  res.statusCode = 404;
  res.statusMessage = 'Not Fount';
  res.end('not fount');
});

function readFile(filepath) {
  return fs.readFileSync(filepath, 'utf8');
}

server.listen(3000, () => console.log('listen in 3000...'))
